//
//  ByShopCarVC.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/26.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByShopCarVC.h"

// vc
#import "ByShopCarSettleVC.h"

// view
#import "ByViewShopCarToolBar.h"
#import "ByViewShopCarStoreHeader.h"

// cell
#import "ByCellShopCarListItem.h"

// model
#import "ByModelShopCarStore.h"

@interface ByShopCarVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) ByViewShopCarToolBar *toolBar;

@property (nonatomic, strong) NSMutableArray *items;

@end

@implementation ByShopCarVC

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"购物车";
    
    [self createViews];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.table.mj_header beginRefreshing];
}

#pragma mark - 懒加载
- (NSMutableArray *)items {
    
    if (!_items) {
        _items = [NSMutableArray new];
    }
    return _items;
}

#pragma mark - 请求数据
- (void)getData {
    
    // 模拟数据
    [_items removeAllObjects];
    
    ByModelShopCarStore *storeModel1 = [ByModelShopCarStore new];
    storeModel1.selected = false;
    storeModel1.name = @"耐克旗舰店";
    storeModel1.tags = @[@"积分抵扣", @"自营"];
    
    ByModelShopCarProductInStore *productModel1 = [ByModelShopCarProductInStore new];
    productModel1.selected = false;
    productModel1.title = @"耐克最新耐克最新耐克最新耐克最新耐克最新";
    productModel1.price = 8888.88;
    productModel1.originPrice = 9999.99;
    productModel1.count = 4;
    productModel1.transfer = @"自取";
    
    ByModelShopCarProductInStore *productModel2 = [ByModelShopCarProductInStore new];
    productModel2.selected = false;
    productModel2.title = @"电热水卡电热水壶";
    productModel2.price = 666.66;
    productModel2.originPrice = 888.88;
    productModel2.count = 1;
    productModel2.transfer = @"快递";
    
    storeModel1.products = @[productModel1, productModel2];

    
    ByModelShopCarStore *storeModel2 = [ByModelShopCarStore new];
    storeModel2.selected = false;
    storeModel2.name = @"天阳电器";
    storeModel2.tags = @[];
    
    ByModelShopCarProductInStore *productModel3 = [ByModelShopCarProductInStore new];
    productModel3.selected = false;
    productModel3.title = @"保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子保暖裤子";
    productModel3.price = 8888.88;
    productModel3.originPrice = 9999.99;
    productModel3.count = 4;
    productModel3.transfer = @"自取";

    storeModel2.products = @[productModel3];
    
    
    [self.items addObject:storeModel1];
    [self.items addObject:storeModel2];
    
    // 每次选中一个商品后都要判断是否全选了
    [self checkIsSelectAll];
    // 计算总价
    [self calculatedTotalPrice];
    [self.table reloadData];
    [self.table.mj_header endRefreshing];
}

#pragma mark - 创建视图
- (void)createViews {
    
    // 工具栏
    _toolBar = [[ByViewShopCarToolBar alloc] init];
    [self.view addSubview:_toolBar];
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@49);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-49);
        } else {
            make.bottom.equalTo(@-49);
        }
    }];
    __weak typeof(self) wself = self;
    _toolBar.selectAllBlock = ^(BOOL selected) {
        [wself selectAllStore:selected];
    };
    _toolBar.settleBlock = ^{
        [wself settle];
    };
    // table
    self.table = [[UITableView alloc] init];
    self.table.backgroundColor = BY_BG_COLOR;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        make.bottom.equalTo(_toolBar.mas_top);
    }];
    self.table.mj_header = [ByCoreRefreshGifHeader headerWithRefreshingBlock:^{
        [self getData];
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.items.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    ByModelShopCarStore *storeModel = self.items[section];
    return storeModel.products.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ByCellShopCarListItem *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[ByCellShopCarListItem alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.modifyBlock = ^ (int count) {
            
            ByModelShopCarStore *storeModel = self.items[indexPath.section];
            ByModelShopCarProductInStore *productModel = storeModel.products[indexPath.row];
            productModel.count = count;
            // 计算总价
            [self calculatedTotalPrice];
            
            [self.table reloadData];
        };
        cell.selectBlock = ^ (BOOL selected) {
            
            ByModelShopCarStore *storeModel = self.items[indexPath.section];
            ByModelShopCarProductInStore *productModel = storeModel.products[indexPath.row];
            productModel.selected = selected;
            
            // 判断商铺是否全选
            [self checkProductInStoreIsSelectAll:storeModel];
            // 每次选中一个商品后都要判断是否全选了
            [self checkIsSelectAll];
            // 计算总价
            [self calculatedTotalPrice];
            
            [self.table reloadData];
        };
    }
    
    ByModelShopCarStore *storeModel = self.items[indexPath.section];
    ByModelShopCarProductInStore *productModel = storeModel.products[indexPath.row];
    cell.model = productModel;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 170;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    ByViewShopCarStoreHeader *header = [[ByViewShopCarStoreHeader alloc] init];
    
    // 设置属性
    ByModelShopCarStore *storeModel = self.items[section];
    header.model = storeModel;

    // 选中回调
    header.selectBlock = ^ (BOOL selected) {
        
        ByModelShopCarStore *storeModel = self.items[section];
        storeModel.selected = selected;
        [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
            productModel.selected = selected;
        }];
        
        // 每次选中一个商品后都要判断是否全选了
        [self checkIsSelectAll];
        // 计算总价
        [self calculatedTotalPrice];
        
        [self.table reloadData];
    };
    
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}


#pragma mark - 点击事件
// 工具栏-全选
- (void)selectAllStore:(BOOL)selected {
    
    [self.items enumerateObjectsUsingBlock:^(ByModelShopCarStore *storeModel, NSUInteger idx, BOOL * _Nonnull stop) {
        storeModel.selected = selected;
        [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
            productModel.selected = selected;
        }];
    }];
    [self.table reloadData];
    // 计算总价
    [self calculatedTotalPrice];
}

// 工具栏-结算
- (void)settle {
    
    // 找到被选中的model
    __block NSMutableArray *selectedItems = [NSMutableArray new];
    [self.items enumerateObjectsUsingBlock:^(ByModelShopCarStore *storeModel, NSUInteger idx, BOOL * _Nonnull stop) {
        // 如果店铺被选中，则说明内部的商品全部被选中
        if (storeModel.selected) {
            [selectedItems addObject:storeModel];
        }
        // 否则找到内部选中的商品，如果没有则不添加
        else {
            __block BOOL hasSelectedProduct = false;
            __block NSMutableArray *selectedProducts = storeModel.products.mutableCopy;
            [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
                
                if (productModel.selected) {
                    hasSelectedProduct = true;
                } else {
                    [selectedProducts removeObject:productModel];
                }
            }];
            
            
            if (hasSelectedProduct) {
                storeModel.products = selectedProducts.copy;
                [selectedItems addObject:storeModel];
            }
        }
    }];
    
    
    ByShopCarSettleVC *vc = [ByShopCarSettleVC new];
    vc.items = selectedItems.copy;
    [self by_normalPush:vc hasNavi:true];
}

#pragma mark - 其他辅助
// 计算总价
- (void)calculatedTotalPrice {
    
    __block CGFloat total = 0.0;
    [self.items enumerateObjectsUsingBlock:^(ByModelShopCarStore *storeModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
            
            // 算入总价
            if (productModel.selected) {
                
                total += (productModel.price * productModel.count);
            }
        }];
    }];
    
    self.toolBar.totalPrice = total;
}
// 判断是否某个商铺全选
- (void)checkProductInStoreIsSelectAll:(ByModelShopCarStore *)storeModel {
    
    __block BOOL isSelectAll = true;
    
    [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (productModel.selected == false) {
            
            isSelectAll = false;
            *stop = true;
        }
    }];
    
    storeModel.selected = isSelectAll;
}

// 判断是否全选了
- (void)checkIsSelectAll {
    
    __block BOOL isSelectAll = true;

    if (self.items.count == 0) {
        isSelectAll = false;
    }
    
    [self.items enumerateObjectsUsingBlock:^(ByModelShopCarStore *storeModel, NSUInteger idx, BOOL * _Nonnull stop) {
        // 如果店铺model为未选中，则一定不是全选的
        if (storeModel.selected == false) {
            isSelectAll = false;
            *stop = true;
        }
        // 如果店铺为选中，则判断旗下商品是否都为选中
        else {
            [storeModel.products enumerateObjectsUsingBlock:^(ByModelShopCarProductInStore *productModel, NSUInteger idx, BOOL * _Nonnull stop) {
                
                // 算入总价
                if (productModel.selected == false) {
                    
                    isSelectAll = false;
                    *stop = true;
                }
            }];
        }

    }];
    self.toolBar.selectAll = isSelectAll;
}

@end
